/**
 * Copyright (c) 2016-Now http://www.javamis.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 */
package com.javamis.modular.system.controller;


import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.javamis.config.shiro.ShiroInfo;
import com.javamis.config.shiro.ShiroUtils;
import com.javamis.modular.system.dao.MenuMapper;
import com.javamis.modular.system.entity.MenuData;

import org.springframework.ui.Model;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @name:   系统Controller层
 * @version:1.0.2
 * @author:	HuiJia
 * @QQ号： 	763236277
 * @QQ群： 	327773608
 * @邮箱: 	javamis@163.com
 * @site：	http://www.javamis.com
 */
// 注意：我们之前用的注解是@RestController ,这个注解相当于@Controller  +  @ResponseBody,表示标注的类或则方法返回的都是json格式的，
// 而我们这次需要访问html页面所以需要换成@Controller注解。在需要的返回json格式的方法上添加@ResponseBody就好，而不是整个类的所有方法都返回json格式。
//@RestController
@Controller
//@RequestMapping("")
public class SystemController {
    @Autowired
    private MenuMapper menuMapper;
    //重定向
    //private static String redirect = "redirect:";
    /**
     * 访问index页面
	* @param model
	* @return
	*/
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(HttpServletResponse response) {
//		Subject subject = SecurityUtils.getSubject();
//		ShiroInfo shiroInfo = (ShiroInfo)SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
//		boolean isAuthority = subject.isAuthenticated();
		if(ShiroUtils.hasAuthority()) {
			//return redirect+"/";
			ShiroUtils.logout();
			ShiroUtils.redirectUrl(response,"/");
		}
		return "login";
	}
    
    /**
               * 访问index页面
     * @param model
     * @return
     */
    @RequestMapping(value = "/sysLogin", method = RequestMethod.POST)
    public String sysLogin(HttpServletResponse response) {
    	HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    	String username = request.getParameter("userName");	//String username = "cj";
    	String password = request.getParameter("password");	//String password = "123";
        // 在认证提交前准备 token（令牌）
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
        	ShiroUtils.getSubject().login(token);		// 执行认证登陆
        } catch (UnknownAccountException uae) {
        	throw new UnknownAccountException("未知账户");
            //return "未知账户";
        } catch (IncorrectCredentialsException ice) {
        	throw new IncorrectCredentialsException("密码不正确");
            //return "密码不正确";
        } catch (LockedAccountException lae) {
        	throw new LockedAccountException("账户已锁定");
            //return "账户已锁定";
        } catch (ExcessiveAttemptsException eae) {
        	throw new ExcessiveAttemptsException("用户名或密码错误次数过多");
            //return "用户名或密码错误次数过多";
        } catch (AuthenticationException ae) {
        	throw new AuthenticationException("用户名或密码不正确!");
            //return "用户名或密码不正确！";
        }
        ShiroInfo shiroInfo = ShiroUtils.getShiroInfoObj();
        if (ShiroUtils.hasAuthority()&&shiroInfo !=null) {
            System.out.println("登录成功");
            //ShiroInfo shiroInfo = (ShiroInfo)SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
            request.getSession().setAttribute("shiroInfo", shiroInfo);
            request.getSession().setAttribute("userCode", shiroInfo.getUserCode());
            request.getSession().setAttribute("userName", shiroInfo.getUserName());
            request.getSession().setAttribute("userId", shiroInfo.getId());
            return "redirect:"+"/";
            //ShiroUtils.redirectUrl(response,"/");
        } else {
            token.clear();
            return "登录失败";
        }
        //return "登录失败";
    }
        
    /**
     * 访问index页面
	* @param model
	* @return
	*/
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String index(Model model) {
//		ShiroInfo shiroInfo = (ShiroInfo) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
//		shiroInfo.getRoleIds();
		ShiroInfo shiroInfo = ShiroUtils.getShiroInfoObj();
		if(shiroInfo.getRoleIdList().size()>0) {
			model.addAttribute("roleIds",shiroInfo.getRoleIds());
			return "index";
		}else {
			ShiroUtils.logout();
			return "login";
		}
	}

    /**
     * 退出当前账户
     * @return
     */
	@RequestMapping(value = "/outLogin", method = RequestMethod.GET)
	public String outLogin(HttpServletResponse response) {
		if(ShiroUtils.logout()) {
			//return "redirect:"+"/login";
			ShiroUtils.redirectUrl(response,"/login");
		}
		return null;
	}
    
    /**
     * 获取菜单Json对象.
     * @param model
     * @return
     */
    @RequestMapping(value="/menus",method = RequestMethod.GET)
    @ResponseBody
    public Object menus(@RequestParam("roleIds") String roleIds) {
    	String roleIdss = roleIds.substring(0, roleIds.length()-1);
    	List<Integer> roleLists = new ArrayList<Integer>();
    	if(roleIdss.contains(",")) {
    		String[] roleArray = roleIdss.split(",");
        	for(String s:roleArray) {
        		roleLists.add(Integer.valueOf(s));
        	}
    	}else {
    		roleLists.add(Integer.valueOf(roleIdss));
    	}
    	
//    	roleLists.add(11);
//    	roleLists.add(14);
    	List<MenuData> menuDatas = new ArrayList<MenuData>();
    	try {
    		menuDatas = menuMapper.getMenusByRoles(roleLists);
    	}catch(Exception e) {
    		System.out.println("根据角色id: "+roleLists +" 获取菜单列表失败，原因是调用menuMapper.getMenusByRoles(List<Integer> roleIds)方法失败 ");
    		 System.out.println(e); 
    	}
	   	 
	   	 //Object o = JSON.parse(menuDatas.toString());
	   	 System.out.println(menuDatas);
	   	JSONArray jsonArray = new JSONArray();
	   	for(MenuData menuData:menuDatas) {
	   		JSONObject json = new JSONObject();
		   	json.put("F_ModuleId", menuData.getF_ModuleId());
		   	json.put("F_ParentId", menuData.getF_ParentId());
//		   	json.put("F_EnCode", menuData.getF_EnCode());
		   	json.put("F_FullName", menuData.getF_FullName());
		   	json.put("F_Icon", menuData.getF_Icon());
		   	json.put("F_UrlAddress", menuData.getF_UrlAddress());
//		   	json.put("F_Target", menuData.getF_Target());
		   	json.put("F_SysMenu", menuData.getF_SysMenu());
//		   	json.put("F_AllowExpand", menuData.getF_AllowExpand());
		   	jsonArray.add(json);
	   	}	
	   	System.out.println(jsonArray.toString());
    	return jsonArray;
    }
    
    
    /**
     * 访问right页面
     * @param model
     * @return
     */
    @RequestMapping(value = "/right", method = RequestMethod.GET)
    public String def(Model model) {
        return "system/include/right";
    }
    
    /**
     * 访问right页面
     * @param model
     * @return
     */
    @RequestMapping(value = "/rightTest", method = RequestMethod.GET)
    public String rightTest(Model model) {
        return "system/include/rightTest";
    }

}
